using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Linq;
using System.Runtime.CompilerServices;

namespace MedicalReportAssistant.Views
{
    public partial class LogWindow : Window
    {
        private TextWriter _textWriter;
        private static LogWindow? _instance;

        public static LogWindow Instance
        {
            get
            {
                if (_instance == null || !IsWindowOpen(_instance))
                {
                    _instance = new LogWindow();
                }
                return _instance;
            }
        }

        private static bool IsWindowOpen(Window window)
        {
            return Application.Current.Windows.Cast<Window>().Any(w => w == window);
        }

        public LogWindow()
        {
            InitializeComponent();
            
            // 创建自定义的TextWriter
            _textWriter = new LogTextWriter(this);
            Console.SetOut(_textWriter);

            // 窗口关闭时恢复默认输出
            this.Closed += (s, e) =>
            {
                Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
            };
        }

        public void AppendText(string text)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(() => AppendText(text));
                return;
            }
            LogTextBox.AppendText($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {text}");
            LogTextBox.ScrollToEnd();
        }

        public void LogError(
            string message,
            [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "",
            [System.Runtime.CompilerServices.CallerLineNumber] int callerLineNumber = 0,
            [System.Runtime.CompilerServices.CallerMemberName] string callerMemberName = "")
        {
            var fileName = System.IO.Path.GetFileName(callerFilePath);
            var logMessage = $"[ERROR] [{fileName}:{callerLineNumber} in {callerMemberName}] {message}\n";
            AppendText(logMessage);
        }

        public void LogInfo(
            string message,
            [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "",
            [System.Runtime.CompilerServices.CallerLineNumber] int callerLineNumber = 0,
            [System.Runtime.CompilerServices.CallerMemberName] string callerMemberName = "")
        {
            var fileName = System.IO.Path.GetFileName(callerFilePath);
            var logMessage = $"[INFO] [{fileName}:{callerLineNumber} in {callerMemberName}] {message}\n";
            AppendText(logMessage);
        }

        public void LogWarning(
            string message,
            [System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "",
            [System.Runtime.CompilerServices.CallerLineNumber] int callerLineNumber = 0,
            [System.Runtime.CompilerServices.CallerMemberName] string callerMemberName = "")
        {
            var fileName = System.IO.Path.GetFileName(callerFilePath);
            var logMessage = $"[WARN] [{fileName}:{callerLineNumber} in {callerMemberName}] {message}\n";
            AppendText(logMessage);
        }

        private class LogTextWriter : TextWriter
        {
            private LogWindow _logWindow;
            private StringBuilder _lineBuffer;

            public LogTextWriter(LogWindow logWindow)
            {
                _logWindow = logWindow;
                _lineBuffer = new StringBuilder();
            }

            public override void Write(char value)
            {
                if (value == '\n')
                {
                    _logWindow.AppendText(_lineBuffer.ToString() + Environment.NewLine);
                    _lineBuffer.Clear();
                }
                else
                {
                    _lineBuffer.Append(value);
                }
            }

            public override Encoding Encoding => Encoding.UTF8;
        }
    }
} 